from django.http import HttpResponse, JsonResponse
from django.utils.deprecation import MiddlewareMixin
from jwt import ExpiredSignatureError, InvalidTokenError, PyJWTError
from rest_framework_jwt.settings import api_settings
from datetime import datetime, timedelta
import jwt


class JwtAuthenticationMiddleware(MiddlewareMixin):
    # 默认token过期时间设置为7天
    DEFAULT_EXPIRATION = timedelta(days=7)

    def process_request(self, request):
        white_list = ["/user/login"]
        path = request.path

        if path not in white_list and not path.startswith("/media"):
            token = request.META.get('HTTP_AUTHORIZATION', '').split(' ')[-1]

            try:
                # 获取解码处理器
                jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
                payload = jwt_decode_handler(token)

                # 检查自定义过期时间（兼容不同签发方式）
                exp_timestamp = payload.get('exp')
                print (exp_timestamp)
                if exp_timestamp:
                    expiration_time = datetime.fromtimestamp(exp_timestamp)
                    print (expiration_time)
                    print (datetime.utcnow())
                    if datetime.utcnow() > expiration_time:
                        return JsonResponse({
                            'code': 401,
                            'message': f'Token已过期（过期时间: {expiration_time}）'
                        }, status=401)

            except ExpiredSignatureError:
                return JsonResponse({
                    'code': 401,
                    'message': 'Token已过期',
                    'solution': '请重新登录获取新token'
                }, status=401)
            except InvalidTokenError:
                return JsonResponse({
                    'code': 403,
                    'message': '无效Token'
                }, status=403)
            except PyJWTError as e:
                return JsonResponse({
                    'code': 400,
                    'message': f'Token验证异常: {str(e)}'
                }, status=400)
            except Exception as e:
                return JsonResponse({
                    'code': 500,
                    'message': f'服务器处理Token时出错: {str(e)}'
                }, status=500)
        return None
